//
//  SearchRootController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/11/24.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "SearchRootController.h"
//untils
#import "Global.h"
#import "UIColor+Hex.h"
#import "AppDelegate.h"
#import "RDVTabBarController.h"
#import "UIImage+ColorToImage.h"
#import "NSString+Conversion.h"
//controller
#import "SearchHistoryController.h"
#import "SearchResultController.h"
#import "MTA.h"

@interface SearchRootController ()
{
    NSString *_keyword;
    NSString *_keywordID;
}
@property (nonatomic,strong)NSArray  *controllerItemsArray;//所有的controller
@property (nonatomic,assign)NSInteger currentIndexOfController;//当前选择的controller的index
@property (nonatomic,assign)NSInteger oldIndexOfController;//上次选择的index
@property (nonatomic, strong)UISearchBar *searchBarView;
@property (nonatomic)BOOL isResultPage;
@end

@implementation SearchRootController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackNavItem];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
    [self setupContainerView];
    [self setupSearchBarView];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //关键字
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startSearch:) name:ksearchHistory object:nil];
    //隐藏键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideKeyword) name:khideSearchKeyboard object:nil];
    AppDelegate *appdelgate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appdelgate.tabBarController setTabBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.searchBarView resignFirstResponder];
    AppDelegate *appdelgate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:ksearchHistory object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:khideSearchKeyboard object:nil];
    [appdelgate.tabBarController setTabBarHidden:NO animated:YES];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"搜索"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"搜索"];
}
#pragma mark -- 初始化搜索框
- (void)setupSearchBarView {
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(54, 0, CGRectGetWidth(self.view.bounds) - 54, 44)];
    bottomView.backgroundColor = [UIColor colorWithHexString:@"#c52720"];
    _searchBarView = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(bottomView.bounds) , 44)];
    _searchBarView.delegate = (id<UISearchBarDelegate>)self;
    _searchBarView.placeholder = @"请输入要搜索的商品";
    UIImage *backgroundImage = [UIImage createImageWithColor:[UIColor colorWithHexString:@"#c52720"] frame:CGRectMake(0, 0,  CGRectGetWidth(bottomView.bounds), 44)];
    [_searchBarView setBackgroundImage:backgroundImage];
    _searchBarView.tintColor=[UIColor lightGrayColor];//设置光标颜色
    [_searchBarView setShowsCancelButton:YES animated:YES];
    //设置取消按钮
    UIButton *btn=[_searchBarView valueForKey:@"_cancelButton"];
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bottomView addSubview:_searchBarView ]   ;
    self.navigationItem.titleView = bottomView;
//    [_searchBarView becomeFirstResponder];
}
#pragma mark -- UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    if (searchBar.text.length == 0) {
        self.currentIndexOfController = 0;
        self.oldIndexOfController = 1;
        [self chengeSubControl];
    }
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:NO animated:YES];
    return YES;
}
//文本输入框，文本改变时的代理方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length == 0 && self.currentIndexOfController == 1) {//当搜索框为空，并且在结果页面
        self.currentIndexOfController = 0;
        self.oldIndexOfController = 1;
        [self chengeSubControl];
    }
}
//点击键盘搜索按钮代理方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self insertObject:searchBar.text toArray:[[self historyDataFromUserdefault] mutableCopy]];
    _keyword = [NSString stringTransformObject:searchBar.text];
    _keywordID = @"";
    [searchBar resignFirstResponder];
    self.currentIndexOfController = 1;
    self.oldIndexOfController = 1;
    [self chengeSubControl];
}
//点击取消按钮代理方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
     [searchBar setShowsCancelButton:NO animated:YES];
    if (self.currentIndexOfController == 0 && !self.isResultPage) {
        [self.searchBarView resignFirstResponder];
        [self.navigationController popViewControllerAnimated:NO];
    } else {
        [self changeSubControlWithSearchType:ksearchResultType];
    }
    
}
#pragma mark -- 初始化容器
- (void)setupContainerView {
    self.currentIndexOfController = 0;
    self.oldIndexOfController = 0;
    //搜索历史
    SearchHistoryController *searchHistoryVC = [[SearchHistoryController alloc]init];
    //搜索结果
    SearchResultController *searchResultVC = [[SearchResultController alloc]init];
    [self addChildViewController:searchHistoryVC];
    [self addChildViewController:searchResultVC];
    self.controllerItemsArray = @[searchHistoryVC,searchResultVC];
    [self chengeSubControl];
}

#pragma mark -- 改变容器显示视图
- (void)changeSubControlWithSearchType:(SearchType)searchType {
    if (searchType == ksearchHistoryType) {
        self.currentIndexOfController = 0;
        self.oldIndexOfController = 1;
    } else if (searchType == ksearchResultType) {
        self.currentIndexOfController = 1;
        self.oldIndexOfController = 0;
    }
    [self.searchBarView resignFirstResponder];
    [self chengeSubControl];
}

- (void)chengeSubControl
{
    //移除一个child view controller
    [(UIViewController*)[_controllerItemsArray objectAtIndex:_oldIndexOfController] willMoveToParentViewController:nil];
    [((UIViewController*)[_controllerItemsArray objectAtIndex:_oldIndexOfController]).view removeFromSuperview];
    [(UIViewController*)[_controllerItemsArray objectAtIndex:_oldIndexOfController] removeFromParentViewController];
    //添加一个child view controller
    
    if (self.currentIndexOfController == 1) {//搜索结果页面
       SearchResultController *currentVC = (SearchResultController*)[_controllerItemsArray objectAtIndex:_currentIndexOfController];
        [self addChildViewController:currentVC];
        CGRect contentFrame = CGRectMake(0
                                         , 0
                                         , CGRectGetWidth(self.view.frame)
                                         , CGRectGetHeight(self.view.frame));
        currentVC.keyword = _keyword;
        currentVC.keywordID = _keywordID;
        currentVC.view.frame = contentFrame;
        [self.view addSubview:currentVC.view];
        [currentVC didMoveToParentViewController:self];

    } else {
        UIViewController *currentVC = [_controllerItemsArray objectAtIndex:_currentIndexOfController];
        [self addChildViewController:currentVC];
        CGRect contentFrame = CGRectMake(0
                                         , 0
                                         , CGRectGetWidth(self.view.frame)
                                         , CGRectGetHeight(self.view.frame));
        currentVC.view.frame = contentFrame;
        [self.view addSubview:currentVC.view];
        [currentVC didMoveToParentViewController:self];
    }
}
#pragma mark -- button Action
- (void)backBtnAction:(id)sender {
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark -- 通知
- (void)startSearch:(NSNotification*)noti {
    NSDictionary *dic = [noti userInfo];
    _isResultPage = YES;
    self.searchBarView.text = [dic objectForKey:ksearchKeyWord];
    _keyword = [NSString stringTransformObject:[dic objectForKey:ksearchKeyWord]];
    _keywordID = [NSString stringTransformObject:[dic objectForKey:ksearchKeyWordId]];
    [self insertObject:self.searchBarView.text toArray:[[self historyDataFromUserdefault] mutableCopy]];
    [self changeSubControlWithSearchType:ksearchResultType];
}

- (void)hideKeyword {
    if ([self.searchBarView isFirstResponder]) {
        [self.searchBarView resignFirstResponder];
    }
}



#pragma mark -- 对历史数据进行处理
//获取历史查询信息
-(NSArray*)historyDataFromUserdefault
{
    if (![[NSUserDefaults standardUserDefaults] objectForKey:ksearchHistory]) {
        NSArray * array = [[NSArray alloc]init];
        [[NSUserDefaults standardUserDefaults] setObject:array forKey:ksearchHistory];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    return [[NSUserDefaults standardUserDefaults] objectForKey:ksearchHistory];
}

//数组是否包含了对象
- (BOOL)judgeString:(NSString*)string wasContainArray:(NSMutableArray*)array
{
    if ([array containsObject:string])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
//插入
-(void)insertObject:(NSString*)object toArray:(NSMutableArray*)array
{
    if ([self judgeString:object wasContainArray:array])//数组已经包含了string,把该string进行重新排序
    {
        [array removeObject:object];
        [array insertObject:object atIndex:0];
        
        
    }
    else
    {
        [array insertObject:object atIndex:0];
        
    }
    [[NSUserDefaults standardUserDefaults] setObject:array forKey:ksearchHistory];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
//移除
-(void)removeObject:(NSString*)object fromArray:(NSMutableArray*)array
{
    if ([self judgeString:object wasContainArray:array])
    {
        NSMutableArray *histoyArray = [NSMutableArray arrayWithArray:array];
        [histoyArray removeObject:object];
        NSArray *storeArr = [histoyArray copy];
        [[NSUserDefaults standardUserDefaults] setObject:storeArr forKey:ksearchHistory];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    else
    {
        return;
    }
    
}

- (void)removeAllObject
{
    NSArray * array = [[NSArray alloc]init];
    [[NSUserDefaults standardUserDefaults] setObject:array forKey:ksearchHistory];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
